package com.zhu.rpc.client.handler;

import com.zhu.rpc.JsonUtil;
import com.zhu.rpc.MsgType;
import com.zhu.rpc.RpcProtocol;
import com.zhu.rpc.client.RpcMsgCallBack;
import com.zhu.rpc.client.RpcRequest;
import com.zhu.rpc.msgBean.RpcResponseBean;
import com.zhu.rpc.msgBean.ServerInitBean;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientHandler extends ChannelInboundHandlerAdapter{
    private String serverName;
    public ClientHandler(String serverName) {
        this.serverName = serverName;
    }
    Logger logger = LoggerFactory.getLogger(ClientHandler.class);

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = ((ByteBuf)msg);
        //取前两位判定消息的类别
        String str = in.toString(CharsetUtil.UTF_8);
        int type = Integer.parseInt(str.substring(0,2));
        MsgType msgType = MsgType.getTypeById(type);
        switch (msgType){
            case heartBeat:
                System.out.println(serverName+" 我特么活的好好地");
                break;
            case callResp:
                RpcResponseBean responseBean = JsonUtil.getObj(str.substring(2),RpcResponseBean.class);
                RpcMsgCallBack msgCallBack = RpcProtocol.msgMap.get(responseBean.getMsgId());
                //通知结果
                if (msgCallBack != null) {
                    msgCallBack.notifyResult(responseBean);
                }
                break;
            case init:
                ServerInitBean serverInitBean = JsonUtil.getObj(str.substring(2),ServerInitBean.class);
                for (String method:serverInitBean.getExposeMethod()){
                    RpcRequest.methodProvideMap.put(method,serverName);
                }
                break;
            default:
                break;
        }
        ctx.fireChannelRead(msg);

    }



}
